from rest_framework_jwt.views import ObtainJSONWebToken

from users.models import User
from rest_framework.generics import RetrieveAPIView,CreateAPIView,UpdateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from meiduo_mall.utils.exceptions import exception_handler
from random import randint
from threading import Thread
from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
from rest_framework.permissions import IsAuthenticated
from users.serializers import UserSerializer, UserDetailSerializers, UserUpdateSerializers
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings
import pickle,base64
from users.utils import merge_cart_cookie_to_redis

# 发送短息的方法
# def send_sms_code(mobile,sms_code):
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)

# Create your views here.



class SMS_CODEView(APIView):
    def get(self, request, mobile):
        # 1、获取前端传递的手机号，路径中进行正则匹配
        print(1111111)
        # 判断前端发送请求的时间间隔 60s
        # 建立连接redis的对象
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'error': '请求过于频繁'}, status=400)
        # 2、生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)
        # 3、保存短信验证码到缓存中
        # string
        pl=conn.pipeline() # 生成管道对象
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        pl.setex('sms_code_flag_%s' % mobile, 60, 1)
        pl.execute() # 连接缓存，传入写入指令
        # 4、发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)
        # t=Thread(target='send_sms_code',kwargs={'mobile':mobile,'sms_code':sms_code})
        # t.start()
        # t.join()
        # 使用celery异步发送短信
        send_sms_code.delay(mobile,sms_code)

        # 5、结果返回
        return Response({'message': 'ok'})

class UserNameView(APIView):
    """
        用户名判断
    """
    def get(self,request,username):
        #1、获取前端数据，正则匹配数据
        #2、根据用户名查询用户对象数量
        count=User.objects.filter(username=username).count()
        #3、返回对象数量
        return Response(
            {
                'count':count,
            }
        )

class MobileView(APIView):
    """
        手机号判断
    """
    def get(self,request,mobile):
        #1、获取前端数据，正则匹配数据
        #2、根据手机号查询用户对象数量
        count=User.objects.filter(mobile=mobile).count()
        #3、返回对象数量
        return Response(
            {
                'count':count,
            }
        )

class UsersView(CreateAPIView):
    """
        注册用户数据
    """
    serializer_class = UserSerializer

class UserDetailView(RetrieveAPIView):
    """
        返回用户信息
    """
    serializer_class = UserDetailSerializers
    permission_classes = [IsAuthenticated] # 权限指定
    # queryset = User.objects.all()
    # 重写get_object 指定返回用户对象
    def get_object(self):
        print(self.request.user)
        return self.request.user

class UserUpdateView(UpdateAPIView):

    """
        更新邮箱
    """
    serializer_class = UserUpdateSerializers

    # 重写get_object 指定返回用户对象
    def get_object(self):
        print(self.request.user)
        return self.request.user

class EmailVerifyView(APIView):
    """
        邮箱验证
    """
    def get(self, request):
        # 1、获取前端数据
        token = request.query_params.get('token')
        # 2、验证数据 解密token
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return Response({'errors': 'token值无效'}, status=400)
        # 3、查询用户
        username = data.get('name')
        try:
            user = User.objects.get(username=username)
        except:
            return Response({'errors': '用户不存在'}, status=400)
        # 4、更新用户邮箱验证状态
        user.email_active = True
        user.save()
        # 5、返回结果
        return Response({'message': True})

class UserLoginView(ObtainJSONWebToken):

    def post(self, request, *args, **kwargs):
        response=super().post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            # 合并购物车
            response=merge_cart_cookie_to_redis(request,user,response)

        return response
